import 'dart:io';

import 'package:flutter/material.dart';
import 'package:home_framework/components/form_util.dart';
import '../../components/button_util.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class DynamicForm extends StatelessWidget {
  final Map<String, Map<String, Object>> formData;
  final Function handleTextFieldChanged;
  final ValueChanged<String> handleClear;
  final String buttonName;
  final Function handleSubmit;
  final File imageFile;
  final String imageUrl;
  final ValueChanged<File> handleImagePicked;
  const DynamicForm(
      this.formData,
      this.handleTextFieldChanged,
      this.handleClear,
      this.buttonName,
      this.handleSubmit,
      this.handleImagePicked,
      {Key key,
      this.imageFile,
      this.imageUrl})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: _getForm(context),
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
      ),
    );
  }

  List<Widget> _getForm(BuildContext context) {
    List<Widget> widgets = [];
    formData.forEach((key, formParams) {
      widgets.add(FormUtil.textField(key, formParams['value'],
          controller: formParams['controller'] ?? null,
          hintText: formParams['hintText'] ?? '',
          prefixIcon: formParams['icon'],
          onChanged: handleTextFieldChanged,
          onClear: handleClear));
    });
    widgets.add(FormUtil.imagePicker(
      'imageUrl',
      () {
        _pickImage(context);
      },
      imageFile: imageFile,
      imageUrl: imageUrl,
    ));

    widgets.add(ButtonUtil.primaryTextButton(
      buttonName,
      handleSubmit,
      context,
      width: MediaQuery.of(context).size.width - 20,
    ));

    return widgets;
  }

  void _pickImage(BuildContext context) async {
    final List<AssetEntity> assets =
        await AssetPicker.pickAssets(context, maxAssets: 1);
    if (assets.length > 0) {
      File file = await assets[0].file;
      handleImagePicked(file);
    }
  }
}
